package com.qk.controller;

import com.qk.anno.Log;
import com.qk.common.PageResult;
import com.qk.common.Result;
import com.qk.dto.BusinessDto;
import com.qk.entity.Business;
import com.qk.service.BusinessService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/businesses")
public class BusinessController {

    @Autowired
    private BusinessService businessService;

    @Log
    @PostMapping
    public Result add(@RequestBody Business business){
        log.info("添加商机");
        business.setCreateTime(LocalDateTime.now());
        business.setUpdateTime(LocalDateTime.now());
        businessService.save(business);
        return Result.success();
    }


    @GetMapping
    public Result listall(BusinessDto businessDto){
        log.info("查询所有商机");
        PageResult<Business> pageResult = businessService.listByBusiness(businessDto);
        return Result.success(pageResult);
    }

    @PutMapping("/assign/{businessId}/{userId}")
    public Result getBusinessById(@PathVariable Integer businessId,@PathVariable Integer userId){
        log.info("分配商机");
        Business business = new Business();
        business.setId(businessId);
        business.setUserId(userId);
        business.setUpdateTime(LocalDateTime.now());
        business.setStatus(2);
        businessService.updateById(business);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result get(@PathVariable Integer id){
        log.info("根据id查询商机");
        Business business = businessService.getBusinessById(id);
        return Result.success(business);
    }

    @Log
    @PutMapping
    public Result update(@RequestBody Business business) throws Exception {
        log.info("更新商机");
        businessService.updateBusinessById(business);
        return Result.success();
    }

    @PutMapping("/back/{id}")
    public Result back(@PathVariable Integer id){
        log.info("商机踢回公海");
        Business business = new Business();
        business.setId(id);
        business.setStatus(4);
        business.setUpdateTime(LocalDateTime.now());
        businessService.updateById(business);
        return Result.success();
    }

    @PostMapping("/toCustomer/{id}")
    public Result toCustomer(@PathVariable Integer id){
        log.info("商机转客户");
        businessService.toCustomer(id);
        return Result.success();
    }

    @GetMapping("/pool")
    public Result pool(BusinessDto businessDto){
        log.info("获取公海池");
        return Result.success(businessService.getpool(businessDto));
    }
}
